package com.freeheart.validation.constraintvalidators.recent;


import java.security.InvalidParameterException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;

/**
 * 针对符合一定日期时间格式的String，计算距离今天的时差
 *
 * @author: EmperorHeart
 * @date: 2025/5/10 1:35
 * @description
 */
public class ComputeGapForDateString implements ComputeGap {

    @Override
    public boolean support(Object obj) {
        return obj instanceof String;
    }

    @Override
    public long compute(Object obj, RecentProperties rp) {
        String dtString = (String) obj;
        // 1.先用LocalDateTime尝试解析
        try {
            LocalDateTime parse = LocalDateTime.parse(dtString, rp.getDateTimeFormatter());
            if (rp.isTruncate()) {
                return rp.currentUnit().between(parse.truncatedTo(rp.currentUnit()),
                        LocalDateTime.now().truncatedTo(rp.currentUnit()));
            }
            return rp.currentUnit().between(parse, LocalDateTime.now());
        } catch (Exception e) {
            // ignore
        }
        // 2.尝试解析失败，使用LocalDate进行解析
        try {
            LocalDate parse = LocalDate.parse(dtString, rp.getDateTimeFormatter());
            return ChronoUnit.DAYS.between(parse, LocalDate.now());
        } catch (DateTimeParseException e) {
            throw new InvalidParameterException(String.format("格式 %s 无法解析字符串 %s ", rp.getFormat(), dtString));
        } catch (Exception e) {
            throw new RuntimeException("字符串日期 " + dtString + "解析失败", e);
        }
    }
}
